
package code.D1215;

/**
 * author : yeswater
 * date : 2023/12/15
 * 
 * 环形链表 II
 * 
 * 返回入环的第一个节点
 * 
 */

public class T142 {
    public ListNode detectCycle(ListNode head) {
        int countF = 0, countS = 0;
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null) {
            if (fast.next == null) {
                return null;
            }
            fast = fast.next.next;
            slow = slow.next;
            countF += 2;
            countS += 2;
            // is loop
            if (fast == slow) {
                break;
            }
        }
        fast = head;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return fast;
    }
    
    private static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
    